<?php
/**
 * Created by 无所谓已
 * User: Administrator
 * Date: 2025-08-26
 * Time: 20:48
 */

namespace app\controller;

use app\common\ClientBaseController;
use app\service\ApiService;
use app\service\ScreenshotService;
use support\Request;

class ApiController extends ClientBaseController
{
    public function checkApi(Request $request)
    {
        return $this->success('ok');
    }

    public function cleanImg(Request $request)
    {
        $service = new ScreenshotService();
        $service->cleanImg();
        return json(['code' => 0, 'msg' => '清理完成', 'data' => array()]);
    }

    public function getImgInfo(Request $request)
    {
        $fileUrl = $request->input('file_url', '');
        $mode = $request->input('mode', 'single'); // single or grid
        $format = $request->input('format', 'png'); // png or jpg
        $count = (int)$request->input('count', 1); // 截图数量

        if (empty($fileUrl)) {
            return json(['code' => 1, 'msg' => '文件地址不能为空']);
        }

        // 验证参数
        if (!in_array($mode, ['single', 'grid'])) {
            return json(['code' => 1, 'msg' => '截图方式参数错误']);
        }

        if (!in_array($format, ['png', 'jpg'])) {
            return json(['code' => 1, 'msg' => '图片格式参数错误']);
        }

//        addlog();
        // 验证截图数量
        if ($mode === 'single') {
            $count = max(1, min(20, $count)); // 限制在1-20之间
        } else {
            $count = 1; // 九宫格模式下count无效
        }

        // 调用服务处理
        $service = new ScreenshotService();
        $result = $service->captureAndUpload($fileUrl, $mode, $format, $count);

        return json($result);
    }

    /**
     * 获取媒体信息
     *
     * @param Request $request
     * @return \support\Response
     */
    public function getMediaInfo(Request $request)
    {
        try {
            // 获取输入参数
            $torrentPath = $request->input('torrent_path');

            // 参数验证
            if (empty($torrentPath)) {
                return $this->fail('缺少必要的参数: torrent_path');
            }

            // 路径安全检查
            if (!ApiService::isValidPath($torrentPath)) {
                return $this->fail('无效的文件路径');
            }

            // 检查文件是否存在
            if (!file_exists($torrentPath)) {
                return $this->fail('指定的文件不存在');
            }

            // 获取媒体信息
            $mediaInfo = getMediaInfo($torrentPath);

            if ($mediaInfo === false) {
                return $this->fail('获取媒体信息失败');
            }

            return $this->success('获取成功', [
                'mediainfo' => $mediaInfo
            ]);

        } catch (\Exception $e) {
            // 记录错误日志
//            logger()->error('获取媒体信息失败: ' . $e->getMessage(), [
//                'exception' => $e,
//                'path' => $torrentPath ?? 'unknown'
//            ]);
            return $this->fail('服务器内部错误');
        }
    }


}